<?php
namespace app\admin\business;
use app\common\model\mysql\AdminUser as AdminUserModel;
use think\Exception;

class AdminUser {

    /**
     * 登录逻辑处理
     * login
     * @param $data
     * @return bool
     * @throws Exception
     */
    public static function login($data)
    {
        try{
            //使用模型沟通数据库
            $message = self::getStatusAttrUsername($data['username']);

            if(empty($message)){
                throw new Exception('用户不存在');
            }
            if($message['password'] != md5($data['password'])){
                throw new Exception('密码不正确');
            }

            //修改登录时间登录ip等信息
            $updateData = [
                'last_time' => time(),
                'last_ip' => request()->ip()
            ];

            $res = AdminUserModel::updateById($message['id'],$updateData);

            if(empty($res)){
                throw new Exception('登录异常');
            }

        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }

        //信息写入session
        session(config("session.session_admin"),$message);
        return true;
    }

    /**
     * 判断后台用户是否存在
     * @param $username
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getStatusAttrUsername($username)
    {
        $adminUser = AdminUserModel::getStatusAttrUsername($username);
        if(empty($adminUser) || $adminUser->status != config("status.admin_login.admin_normal")){
            return false;
        }
        $message = $adminUser->toArray();
        return $message;
    }

    /**
     * 后台用户修改密码
     * @param $data
     * @return bool
     * @throws Exception
     */
    public static function getStatusAttrUpdatePassword($data)
    {
        try{
            $SessionUser = session(config("session.session_admin"));
           // 修改登录时间登录ip秘密等信息
            $updateData = [
                'password' => md5($data['newpass']),
                'last_time' => time(),
                'last_ip' => request()->ip()
            ];
            $res = AdminUserModel::updateByPassword($SessionUser['username'],$updateData);
            if(empty($res)){
                throw new Exception('处理异常');
            }
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }

        //清除session
        session(config("session.session_admin"),null);
        return true;
    }

}